<?php

// 公共助手函数

use think\exception\HttpResponseException;
use think\Response;

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param string | array  $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int    $size      大小
     * @param string $delimiter 分隔符
     * @param int    $precision 小数位数
     * @return string
     */
    function format_bytes($size, $delimiter = '', $precision = 2)
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 5; $i++) {
            $size /= 1024;
        }
        return round($size, $precision) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int    $time   时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time  时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $cdnurl = \think\Config::get('upload.cdnurl');
        if (is_bool($domain) || stripos($cdnurl, '/') === 0) {
            $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
        }
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items  数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = $v['field'] ?? $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = $v['display'] ?? str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = $v['primary'] ?? '';
            $v['column'] = $v['column'] ?? 'name';
            $v['model'] = $v['model'] ?? '';
            $v['table'] = $v['table'] ?? '';
            $v['name'] = $v['name'] ?? str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                // 优先判断使用table的配置
                $model = $v['table'] ? \think\Db::table($v['table']) : \think\Db::name($v['name']);
            }
            $primary = $v['primary'] ?: $model->getPk();
            $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column($v['column'], $primary) : [];
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $linedata = array_intersect_key($result[$n], $curr);
                    $v[$fieldsArr[$n]['display']] = $fieldsArr[$n]['column'] == '*' ? $linedata : implode(',', $linedata);
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 使用短标签打印或返回数组结构
     * @param mixed   $data
     * @param boolean $return 是否返回数据
     * @return string
     */
    function var_export_short($data, $return = true)
    {
        return var_export($data, $return);
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}

if (!function_exists('check_nav_active')) {
    /**
     * 检测会员中心导航是否高亮
     */
    function check_nav_active($url, $classname = 'active')
    {
        $auth = \app\common\library\Auth::instance();
        $requestUrl = $auth->getRequestUri();
        $url = ltrim($url, '/');
        return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
    }
}

if (!function_exists('check_cors_request')) {
    /**
     * 跨域检测
     */
    function check_cors_request()
    {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] && config('fastadmin.cors_request_domain')) {
            $info = parse_url($_SERVER['HTTP_ORIGIN']);
            $domainArr = explode(',', config('fastadmin.cors_request_domain'));
            $domainArr[] = request()->host(true);
            if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
                header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            } else {
                $response = Response::create('跨域检测无效', 'html', 403);
                throw new HttpResponseException($response);
            }

            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');

            if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
                }
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                }
                $response = Response::create('', 'html');
                throw new HttpResponseException($response);
            }
        }
    }
}

if (!function_exists('xss_clean')) {
    /**
     * 清理XSS
     */
    function xss_clean($content, $is_image = false)
    {
        return \app\common\library\Security::instance()->xss_clean($content, $is_image);
    }
}

if (!function_exists('url_clean')) {
    /**
     * 清理URL
     */
    function url_clean($url)
    {
        if (!check_url_allowed($url)) {
            return '';
        }
        return xss_clean($url);
    }
}

if (!function_exists('check_ip_allowed')) {
    /**
     * 检测IP是否允许
     * @param string $ip IP地址
     */
    function check_ip_allowed($ip = null)
    {
        $ip = is_null($ip) ? request()->ip() : $ip;
        $forbiddenipArr = config('site.forbiddenip');
        $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
        $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
        if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
            $response = Response::create('请求无权访问', 'html', 403);
            throw new HttpResponseException($response);
        }
    }
}

if (!function_exists('check_url_allowed')) {
    /**
     * 检测URL是否允许
     * @param string $url URL
     * @return bool
     */
    function check_url_allowed($url = '')
    {
        //允许的主机列表
        $allowedHostArr = [
            strtolower(request()->host())
        ];

        if (empty($url)) {
            return true;
        }

        //如果是站内相对链接则允许
        if (preg_match("/^[\/a-z][a-z0-9][a-z0-9\.\/]+((\?|#).*)?\$/i", $url) && substr($url, 0, 2) !== '//') {
            return true;
        }

        //如果是站外链接则需要判断HOST是否允许
        if (preg_match("/((http[s]?:\/\/)+((?>[a-z\-0-9]{2,}\.)+[a-z]{2,8}|((?>([0-9]{1,3}\.)){3}[0-9]{1,3}))(:[0-9]{1,5})?)(?:\s|\/)/i", $url)) {
            $chkHost = parse_url(strtolower($url), PHP_URL_HOST);
            if ($chkHost && in_array($chkHost, $allowedHostArr)) {
                return true;
            }
        }

        return false;
    }
}

if (!function_exists('build_suffix_image')) {
    /**
     * 生成文件后缀图片
     * @param string $suffix 后缀
     * @param null   $background
     * @return string
     */
    function build_suffix_image($suffix, $background = null)
    {
        $suffix = mb_substr(strtoupper($suffix), 0, 4);
        $total = unpack('L', hash('adler32', $suffix, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $background = $background ? $background : "rgb({$r},{$g},{$b})";

        $icon = <<<EOT
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
            <path style="fill:#E2E5E7;" d="M128,0c-17.6,0-32,14.4-32,32v448c0,17.6,14.4,32,32,32h320c17.6,0,32-14.4,32-32V128L352,0H128z"/>
            <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
            <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
            <path style="fill:{$background};" d="M416,416c0,8.8-7.2,16-16,16H48c-8.8,0-16-7.2-16-16V256c0-8.8,7.2-16,16-16h352c8.8,0,16,7.2,16,16 V416z"/>
            <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
            <g><text><tspan x="220" y="380" font-size="124" font-family="Verdana, Helvetica, Arial, sans-serif" fill="white" text-anchor="middle">{$suffix}</tspan></text></g>
        </svg>
EOT;
        return $icon;
    }

    if(!function_exists("randomNumber")){
        function randomNumber()
        {
            return "JJM".rand(100000000,999999999);
        }
    }
}

/**
 * @param array $array 要处理的数组
 * @param array $fields 要处理的字段名
 * @return array
 */
function addWebSiteUrl($array = [], $fields = [])
{
    if (empty($array) || empty($fields)){
        return $array;
    }
    if(count($array) == count($array,1)){
        foreach ($fields as $key => $value) {
            if (!empty($array[$value])) {
                $array[$value] = protocol_name() . '://' . $_SERVER['SERVER_NAME'].$array[$value];
            }
        }
    } else {
        foreach ($array as &$v1) {
            foreach ($fields as &$v2) {
                if (!empty($v1[$v2])) {
                    $v1[$v2] = protocol_name() . '://' . $_SERVER['SERVER_NAME'].$v1[$v2];
                }
            }
        }
    }
    return $array;
}

//生成随机订单号
function generateOrderNumber() {
    $prefix = 'JJM';
    $date = date('YmdHis');
    $random = mt_rand(100000, 999999);
    $order_number = $prefix.$date.$random;
    return $order_number;
}

//生成积分订单4位核销码  $type默认是1，生成积分订单核销码
function generateUniqueCode($length=4,$storeId,$type=1)
{
    $code = '';
    while (true) {
        // 生成4位随机数，首位不为0
        $prefix = $length > 1 ? mt_rand(1, 9) : 0; // 首位不能为0
        $suffix = '';
        for ($i = 1; $i < $length; $i++) {
            $suffix .= mt_rand(0, 9);
        }
        $code = $prefix . $suffix;
        if ($type == 1) {
            $isCodeExist = db('integral_order')->where(['code'=>$code,'store_id'=>$storeId])->find();
        } else {
            $isCodeExist = db('order')->where(['ti_code'=>$code,'store_id'=>$storeId])->find();
        }
        if (empty($isCodeExist)) { // 检查码是否已存在
            break;
        }
    }
    return $code;
}

/**
 *  curl get 请求
 * @param string $url       基于的baseUrl
 * @param int $flag         标志位, 是否验证ssl
 * @return string           返回的资源内容
 **/
function curlGet($url, $flag = 0){
    $ch = curl_init();
    if(! $flag) curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_URL, $url);
    $response = curl_exec($ch);
    curl_close($ch);
    //-------请求为空
    if(empty($response)){
        return null;
    }

    return $response;
}

/**
 *  curl post 发短信专用的请求
 * @param string $url       基于的baseUrl
 * @param array $data       请求的参数列表
 * @param int $flag         标志位, 是否验证ssl
 * @return string           返回的资源内容
 **/
function curlPosts($url,$postFields){
    $postFields = json_encode($postFields);
    $ch = curl_init ();
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8'
        )
    );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt( $ch, CURLOPT_POST, 1 );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields);
    curl_setopt( $ch, CURLOPT_TIMEOUT,1);
    curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0);
    $ret = curl_exec ( $ch );
    // var_dump($ret);
    if (false == $ret) {
        $result = curl_error(  $ch);
    } else {
        $rsp = curl_getinfo( $ch, CURLINFO_HTTP_CODE);
        if (200 != $rsp) {
            $result = "请求状态 ". $rsp . " " . curl_error($ch);
        } else {
            $result = $ret;
        }
    }
    curl_close ( $ch );
    return $result;
}


/**
 *  curl post 请求
 * @param string $url       基于的baseUrl
 * @param array $data       请求的参数列表
 * @param int $flag         标志位, 是否验证ssl
 * @return string           返回的资源内容
 **/
function curlPost($url, $data, $flag = 0){
    $ch = curl_init();
    if(! $flag) curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    // curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_URL, $url);
    $ret = curl_exec($ch);

    curl_close($ch);
    return $ret;
}

//根据订单金额获取满减金额
function getOrderManJian($activeId,$storeId)
{
    $time = time();
    $active = db('store_active')->where(['id'=>$activeId])->find();
    if (empty($active)) {
        return ['code'=>201,'msg'=>'满减活动不存在'];
    }
    if ($time < strtotime($active['starttime']) || $time > strtotime($active['endtime'])) {
        return ['code'=>201,'msg'=>'当前不在满减活动时间范围内'];
    }
    if ($active['store_id'] !== $storeId) {
        return ['code'=>201,'msg'=>'非法活动'];
    }
    return ['code'=>200,'msg'=>'获取成功','data'=>[
        'full_price'=>$active['full_price'],
        'minus_price'=>$active['minus_price']
    ]];
}

/************各种返利，首购复购相关**************/

/**
 *本次采购是否为首购
 *$setGoods 所有产品id
 *$setNum 所有产品数量
 *$type 采购方式
 *$firstStorageBalance 剩余首购金额
 **/
function isFirst($setGoods,$setNum,$type,$firstStorageBalance)
{
    $isFirst = 1;//默认首购
    $shouGouPrice = 0;//首购需要花的money
    foreach ($setGoods AS $key => $value) {
        $goods = db('goods')->where('id',$value)->find();
        //1=用户零售,2=合伙人零售,3=合伙人采购,4=空间采购,5=中心采购
        $oneRatio = 0;

        switch ($type) {
            //合伙人采购
            case 3:
                $oneRatio = $goods['partner_discount_first'];
                break;
            //空间采购
            case 2:
                $oneRatio = $goods['space_discount_first'];

                break;
            //中心采购
            case 1:
                $oneRatio = $goods['center_discount_first'];
                break;
        }
        $shouGouPrice+=round($goods['price']*($oneRatio/100),2)*$setNum[$key];
    }


    if ($shouGouPrice > $firstStorageBalance) {
        $isFirst = 2;//复购
    }
    return $isFirst;
}

/**
 *获取产品采购比例
 *$goods 产品信息
 *$type 采购方式
 *$isFirst 1首购  2复购
 **/
function getGoodsCaiRatio($goods,$type,$isFirst)
{
    $ratio = 0;//采购折扣比例
    switch ($type) {
        //合伙人采购
        case 3:
            $ratio = $goods['partner_discount_first'];
            if ($isFirst == 2) {
                //复购
                $ratio = $goods['partner_discount'];
            }
            break;
        //空间采购
        case 2:
            $ratio = $goods['space_discount_first'];
            if ($isFirst ==2) {
                //复购
                $ratio = $goods['space_discount'];
            }
            break;
        //中心采购
        case 1:
            $ratio = $goods['center_discount_first'];
            if ($isFirst == 2) {
                //复购
                $ratio = $goods['center_discount'];
            }
            break;
    }
    return $ratio;
}

/**
 *获取合伙人，推广比例
 *$type 采购方式
 *$isFirst 1首购  2复购
 *$store 空间/中心信息
 **/
function getGoodsTuiPartnerRatio($isFirst)
{
    $tgRatio = 0;
    if ($isFirst == 1) {
        //合伙人首购推广比例
        $tgRatio = db('config')->where(['name'=>'partner_first','group'=>'basic'])->value('value');
    } else {
        //复购
        $tgRatio = db('config')->where(['name'=>'partner_fu','group'=>'basic'])->value('value');
    }
    return $tgRatio;
}

/**
 *获取中心/空间，推广比例
 *$type 采购方式
 *$isFirst 1首购  2复购
 *$store 空间/中心信息
 **/
function getGoodsTuiRatio($type,$isFirst,$store)
{
    $tgRatio = 0;//推广人推广比例
    $tgCenterRatio = 0;//推广人上级中心推广比例
    $centerRatioFirst = db('config')->where(['name'=>'center_first','group'=>'basic'])->value('value');//中心首购推广比例
    $centerRatioFu = db('config')->where(['name'=>'center_fu','group'=>'basic'])->value('value');//中心复购推广比例
    $kongJianRatioFirst = db('config')->where(['name'=>'store_first','group'=>'basic'])->value('value');//空间首购推广比例
    $kongJianRatioFu = db('config')->where(['name'=>'store_fu','group'=>'basic'])->value('value');//空间复购推广比例
    $storeFuLittle = db('config')->where(['name'=>'store_fu_little','group'=>'basic'])->value('value');//当有上级时使用

    $tgRatio = 0;
    $tgCenterRatio = 0;
    
    switch ($type) {
        //1=中心
        case 1:
            if ($isFirst == 1) {
                //首购
                $tgRatio = $centerRatioFirst;
            } else {
                //复购
                $tgRatio = $centerRatioFu;
            }
            break;
        //2=空间
        case 2:
            if ($isFirst == 1) {
                //首购
                $tgRatio = $kongJianRatioFirst;
            } else {
                //复购
                $tgRatio = $kongJianRatioFu;
            }
            break;
        //3=合伙人
        case 3:
            if ($isFirst == 1) {
                //合伙人首购推广比例
                $tgRatio = db('config')->where(['name'=>'partner_first','group'=>'basic'])->value('value');
            } else {
                //复购
                $tgRatio = db('config')->where(['name'=>'partner_fu','group'=>'basic'])->value('value');
            }
            break;
    }

    //上级和推广人不是同一个人 && 是复购
    if (!empty($store['pid']) && $store['pid'] !== $store['promotion_id'] && $isFirst == 2) {
        //当有上级中心时，把推广人比例给上级中心
        $tgCenterRatio = $tgRatio;
        //推广人比例变为另一个设置的比例
        $tgRatio = $storeFuLittle;
    }

    if (empty($store['promotion_id'])) {
        $tgRatio = 0;
    }
        
    return [
        'tgRatio'=>$tgRatio,
        'tgCenterRatio'=>$tgCenterRatio
    ];
}



/**
 *获取产品采购价
 *$goodsId 产品id
 *$type 采购方式
 *$isFirst 1首购  2复购
 **/
function getCaiPrice($goodsId,$type,$isFirst)
{
    $goods = db('goods')->where('id',$goodsId)->find();
    $ratio = 0;//采购折扣比例
    switch ($type) {
        //合伙人采购
        case 3:
            $ratio = $goods['partner_discount_first'];
            if ($isFirst == 2) {
                //复购
                $ratio = $goods['partner_discount'];
            }
            break;
        //空间采购
        case 2:
            $ratio = $goods['space_discount_first'];
            if ($isFirst ==2) {
                //复购
                $ratio = $goods['space_discount'];
            }
            break;
        //中心采购
        case 1:
            $ratio = $goods['center_discount_first'];
            if ($isFirst == 2) {
                //复购
                $ratio = $goods['center_discount'];
            }
            break;
    }
    $goodsPay = round($goods['price']*($ratio/100),2);//采购价
    return $goodsPay;
}

/**
 *获取中心/空间推广佣金
 *$goods 产品信息
 *$type 采购方式
 *$isFirst 1首购  2复购
 *$store 中心/空间信息
 **/
function getTuiGuangCommission($goods,$type,$isFirst,$store)
{
    $tgRatio = 0;
    $pv = $goods['pv'];//推广佣金按pv去乘比例
    $centerRatioFirst = db('config')->where(['name'=>'center_first','group'=>'basic'])->value('value');//中心首购推广比例
    $centerRatioFu = db('config')->where(['name'=>'center_fu','group'=>'basic'])->value('value');//中心复购推广比例
    $kongJianRatioFirst = db('config')->where(['name'=>'store_first','group'=>'basic'])->value('value');//空间首购推广比例
    $kongJianRatioFu = db('config')->where(['name'=>'store_fu','group'=>'basic'])->value('value');//空间复购推广比例
    $storeFuLittle = db('config')->where(['name'=>'store_fu_little','group'=>'basic'])->value('value');//当有上级时使用
    switch ($type) {
        //1=中心
        case 1:
            if ($isFirst == 1) {
                //首购
                $tgRatio = $centerRatioFirst;
            } else {
                //复购
                $tgRatio = $centerRatioFu;
            }
            break;
        //2=空间
        case 2:
            if ($isFirst == 1) {
                //首购
                $tgRatio = $kongJianRatioFirst;
            } else {
                //复购
                $tgRatio = $kongJianRatioFu;
            }
            break;
    }
    $tuiGuangPidPrice = 0;//空间上级中心推广佣金
    $promotionPrice = 0;//推广人佣金
    $promotionPricePt = 0;//总推广佣金

    //计算推广佣金
    if (empty($store['promotion_id'])) {
        if (!empty($store['pid'])) {
            //上级和推广人不是同一个人 && 是复购
            $tuiGuangPidPrice = round($pv*($tgRatio/100),2);
        }
    } else {
        $promotionPrice = round($pv*($tgRatio/100),2);//推广人佣金
        if (!empty($store['pid']) && $store['pid'] !== $store['promotion_id'] && $isFirst == 2) {
            //上级和推广人不是同一个人 && 是复购
            $tuiGuangPidPrice = round($pv*($tgRatio/100),2);
            $promotionPrice = round($pv*($storeFuLittle/100),2);
        }
    }
    
    $promotionPricePt = $tuiGuangPidPrice+$promotionPrice;

    $backList = [
        'promotionPricePt'=>$promotionPricePt,
        'tuiGuangPrice'=>$promotionPrice,//直接推广人佣金
        'tuiGuangPidPrice'=>$tuiGuangPidPrice,//空间上级中心佣金
    ];
    return $backList;
}

/**
 *获取推广人推广佣金
 *$goods 产品信息
 *$type 采购方式
 *$isFirst 1首购  2复购
 *$store 中心/空间信息
 **/
function getTuiGuangCommissionPartner($goods,$isFirst)
{
    $tgRatio = 0;
    $pv = $goods['pv'];//推广佣金按pv去乘比例
    if ($isFirst == 1) {
        //合伙人首购推广比例
        $tgRatio = db('config')->where(['name'=>'partner_first','group'=>'basic'])->value('value');
    } else {
        //复购
        $tgRatio = db('config')->where(['name'=>'partner_fu','group'=>'basic'])->value('value');
    }
    $promotionPartnerPrice = round($pv*($tgRatio/100),2);//推广人佣金
//    $backList = [
//        'promotionPartnerPrice'=>$promotionPartnerPrice
//    ];
    return $promotionPartnerPrice;
}

/**
 *业务员业绩
 *$goodsId 产品id
 *$type 采购方式
 *$isFirst 1首购  2复购
 **/
function getYeWuCommission()
{
    //业务员业绩
//每个产品净销售额 =（采购价 – 产品PV值*推广分佣比例）*业务员奖金比例；
//    $goodsOnePrice = round(($goodsPay-$pv*($tgRatio/100))*($salesman['bonus_ratio']/100),2);
//    return $goodsOnePrice;
}


/**
 *根据角色重置商品列表的价格
 *$goodsInfo 产品信息
 *$type 角色 1普通用户 2高级用户 3合伙人
 *$useId 指定产品id
 **/
function goodsPriceReset($goodsInfo,$type,$useId='id')
{
    if ($type <= 1 || empty($goodsInfo)) {
        return $goodsInfo;
    }
    if(count($goodsInfo) == count($goodsInfo,1)){
        $goods = db('goods')->where('id',$goodsInfo[$useId])->find();
        $discount1 = 100;
        switch ($type) {
            case 2:
                $discount1 = $goods['highuser_discount'];
                break;
            case 3:
                //这里合伙人零售  和 合伙人采购用的是同一个比例
                $discount1 = $goods['partner_discount'];
                break;
        }
        $goodsInfo['price'] = round($goods['price']*($discount1/100),2);
        return $goodsInfo;
    }else{
        foreach ($goodsInfo AS $key => $value) {

            if (isset($value['highuser_discount']) && isset($value['partner_discount'])) {
                $highuserDiscount = $value['highuser_discount'];
                $partnerDiscount = $value['partner_discount'];
            } else {

                $goods = db('goods')->where('id',$value[$useId])->find();
                $highuserDiscount = $goods['highuser_discount'];
                $partnerDiscount = $goods['partner_discount'];
            }
            $discount1 = 100;
            switch ($type) {
                case 2:
                    $discount1 = $highuserDiscount;
                    break;
                case 3:
                    //这里合伙人零售  和 合伙人采购用的是同一个比例
                    $discount1 = $partnerDiscount;
                    break;
            }
            $goodsInfo[$key]['price'] = round($value['price']*($discount1/100),2);

        }
        return $goodsInfo;
    }

}

//发短信
function duanxin($mobile)
{
    $verify=rand(123456, 999999);//获取随机验证码
    header('Content-Type: text/html; charset=utf-8');

    $account='zhatuche';
    $password='ZhTu862Se';


    $msg='【渣土智慧平台】您好，您的验证码是'.$verify;
    $url ="https://api.mix2.zthysms.com/v2/sendSms";
    $tkey=time();

    $postArr = array (
        'username'  =>  $account,
        'password' =>md5(md5($password).$tkey),
        'tKey' => $tkey,
        'mobile' => $mobile,
        'content' => $msg,

    );

    $result = curlPosts($url, $postArr);
    //var_dump($result);die;
    $data=json_decode($result,true);

    if ($data['code']==200)
    {
        return $verify;
    }
    else
    {
        return false;
    }
}
function write_log($data,$type=''){ 
    // return 1;
    //设置路径目录信息
    
    $url = './log/'.date('Ymd').'_log.txt';
    
    $dir_name=dirname($url);
      //目录不存在就创建
      if(!file_exists($dir_name))
      {
        //iconv防止中文名乱码
       $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
      }
      $fp = fopen($url,"a");//打开文件资源通道 不存在则自动创建       
    fwrite($fp,var_export($data,true)."\r\n");//写入文件
    fclose($fp);//关闭资源通道
}
function gethost()
{
    $host=$_SERVER["HTTP_HOST"];
    return protocol_name() . '://' .$host;
}

//获取下单用户角色
function getOrderRole($orderType,$userType)
{
    $role_type = 0;
    if ($orderType == 1) {
        if ($userType == 1) {
            $role_type =1;
        }
        if ($userType == 2) {
            $role_type =2;
        }
    } elseif ($orderType == 2) {
        //合伙人
        $role_type = 3;
    } elseif ($orderType == 3) {
        //合伙人
        $role_type = 3;
    } elseif ($orderType == 4) {
        //空间
        $role_type = 4;
    } elseif ($orderType == 5) {
        //中心
        $role_type = 5;
    }
    return $role_type;
}
function getstatus()
{
    // 1=终极申请中,2=申请中,3=已通过,4=未通过,5=终极审核未通过
    $statusarr=['待终审','待审核','已通过','未通过','终审未通过'];
    return $statusarr;
}